from random import randrange

from pyecharts.faker import Faker
import time
from pyecharts.charts import Bar
from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
import json
from myapp import models
import pyecharts.options as opts


# Create your views here.


def Result(data):
    result = {}
    if data:
        result['message'] = 'ok'
        result['code'] = '200'
        result['data'] = data
        return result
    result['message'] = '未知错误'
    result['code'] = '500'
    return result


def index(request):
    # 使用post 请求，需要csrf 验证，去seeting 把验证取消了‘
    start = time.time()
    list = models.VideoShow.objects.all()
    a = []
    for i in list:
        dic = {}
        dic['pic'] = i.pic
        dic['author'] = i.author
        a.append(dic)
    result = Result(data=a)
    obj = JsonResponse(result)
    obj['Access-Control-Allow-Origin'] = '*'  # 跨域解决

    print("耗时：", time.time() - start, f"数据:{len(list)}条")
    return obj


def abc(request):
    bar = (
        Bar()
        .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
        .add_yaxis("商家A", [randrange(0, 100) for _ in range(6)])
        .add_yaxis("商家B", [randrange(0, 100) for _ in range(6)])
        .dump_options_with_quotes()  # 獲得json文件
    )
    result = {
        'data': json.loads(bar),
        'message': 'success',
        'code': 200
    }
    response = JsonResponse(
        data=result,
        content_type='application/json'
    )
    # response = HttpResponse(
    #     json.dumps(result),
    #     content_type='application/json'
    # )
    response['Access-Control-Allow-Origin'] = '*'  # 跨域解决

    return response
